<? if ($c = stack('name')) {
	
	$s = component_settings($c);

	$now = parse_today();
	$expires = date("Y-m-d", mktime(0,0,0, $now['m'], $now['d'] + (int)$s['new_user_expires'], $now['y']));;
	
	$_record = array('kind' => TK_CHANGE_MAIL, 'expires' => $expires);


	// validation
	
	$res = array();
	$val = true;
	
	$login = gccUserInfo('email');
	$pass = trim(postdata('pass'));
	
	if (pwd($pass, $login) == gccUserInfo('pass'))
		$res[] = array('pass', true, '');
	else {
		$res[] = array('pass', false, 'Невірний пароль');
		$val = false;
	}
	
	
	
	$newmail = h(trim(postdata('newmail')));

	if ($newmail === '') {
		$res[] = array('newmail', false, 'E-mail має не бути пустим');
		$val = false;
	} else
	
	if (datafetch('db_item', 'cs_person', "email='$newmail'")) {
		$res[] = array('newmail', false, 'Цей e-mail вже зареєстровано, оберіть інший.');
		$val = false;
	}


//debug($newmail);	
//debug($val ? "t" : "f", 'validated');

if ($val) {


	$uuid = gccGetUUID();



	
// ** crafting ticket
	
	$res = array('email' => $newmail, 'old' => $login, 'pass' => pwd($pass, $newmail));
	$res = php2js($res);	

	$recp = 	$email;
	
	datafetch('db_insert', 'cs_ticket', array_merge($_record, array('id' => $uuid, 'data' => $res)));




// ** mail notification

	$tpl_tags = array(
		'expires' => date2str(parse_date($expires), context('lang')),
		'ticket_link' => "http://$_SERVER[SERVER_NAME]:$_SERVER[SERVER_PORT]/$CONTEXT[lang_prefix]register/confirm-newlogin/id-$uuid/",
		'base_url' => "$_SERVER[SERVER_NAME]:$_SERVER[SERVER_PORT]/",
		'old_login' => $login,
		'new_login' => $newmail,
	);

	$se = array(); $re = array();	foreach($tpl_tags as $k => $v) { $se[] = '{'.$k.'}'; $re[] = $v; }

	$t = str_replace($se, $re, $s['mail_change_confirmation']);
	

	try {
		
		$recp = $newmail;
		
		$subject = '=?utf-8?B?'.base64_encode( stripslashes($s['mail_change_confirmation_subj'])).'?=';
		
		$random_hash = md5(date('r', time())); 
		
		$headers = "From: \"=?utf-8?B?".base64_encode( stripslashes($s['mail_sender_name']))."?=\" <$s[mail_sender]>";
	
		$headers .= "\nX-Mailer: PHP/".phpversion();
		$headers .= "\nMIME-Version: 1.0";
		$headers .= "\nContent-Type: multipart/mixed; boundary=\"mixed-".$random_hash."\"";
		$headers .= "\nContent-Transfer-Encoding: base64";
	
		$body = chunk_split(base64_encode(stripslashes($t)));
	
	
		ob_start();

?>
--mixed-<?=$random_hash?>

Content-Type: text/html; charset="utf-8"
Content-Transfer-Encoding: base64

<?=$body?>

--mixed-<?=$random_hash?>--

<?
	
		$body = ob_get_clean();
		
		if (@mail($recp, $subject, $body, $headers, '-f '.stripslashes($s['mail_sender'])))
			diags('<p class="success">Sent</p>');
		else
			throw new Exception('Not sent');
			
	//			exit( str_replace('<', '&lt;', json_encode(array("diags" => implode('', $GLOBALS['DIAGS'])))) );
	
	} catch(Exception $e) {
		diags('<p class="error">'.$e->getMessage().'</p>');
	}





	$res = array(array('newmail', true, ''), array('pass', true, ''));
	
	print(json_encode($res));
	exit;

} else {

// debug('not validated');	
	
	print(json_encode($res));
	exit;
}

unstack();
}